import store from '@/store'
import { message } from 'antd'
import axios from 'axios'
import customHistory from './history'
import { logoutAction } from '@/store/actions/login'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
})

request.interceptors.request.use((config) => {
  // 获取token
  const { token } = store.getState()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config
})

// 简化后台返回数据
request.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    if (error.response.status === 401) {
      message.error(error.response.data.message)
      store.dispatch(logoutAction())
      customHistory.replace({
        pathname: '/login',
        state: {
          from: customHistory.location.pathname,
        },
      })
    }
    return Promise.reject(error)
  }
)

export default request
